package com.xcc.dataStructures.demo06_algorithm;

/**
 * 插入排序
 */
public class InsertionSort {

    public static void main(String[] args) {
//        int[] arr = {1, 3, 10, 5, 6};
        int data = 150000;//15w数据
        int[] arr = new int[data];
        for (int i = 0; i < data; i++) {
            arr[i] = (int) (Math.random() * data);
        }
//        int[] arr = {32, 7, 12, 11, 90, 5, 1};
        long startTime = System.currentTimeMillis();
        insertionSort(arr);
        long endTime = System.currentTimeMillis();
        System.out.println("时长：" + ((endTime - startTime))); //大概耗时1s
    }

    /**
     * 插入排序
     */
    public static void insertionSort(int[] arr) {
        if (arr == null) {
            return;
        }
        int insertval;//需要插入的数据
        int insertIndex;//被插入数组的索引
        for (int i = 0; i < arr.length-1; i++) {
            insertval = arr[i +1];
            insertIndex = i ;
            //如果需要插入的数值小于
            while (insertIndex > 0 && insertval < arr[insertIndex]) {
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex--;
            }
            if (insertIndex != i) {
                arr[insertIndex + 1] = insertval;
            }
        }
    }

}
